package urjc.as.emergencies.client.jpanels.missions;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import net.miginfocom.swing.MigLayout;

import org.restlet.data.Form;
import org.restlet.data.Response;
import org.restlet.data.Status;

import urjc.as.emergencies.client.CommToolkit;
import urjc.as.emergencies.client.DynamicTree;
import urjc.as.emergencies.client.Node;
import urjc.as.emergencies.client.TextArea;
import urjc.as.emergencies.data.AmbulanceList;
import urjc.as.emergencies.data.Mission;
import urjc.as.emergencies.data.MissionList;

/**
 * Panel que gestiona las peticiones a misión. Permite la edición del: <li>
 * Estado <li>Ambulancia asignada
 * 
 * @author ahiges
 * 
 */
@SuppressWarnings("serial")
public class PanelMission extends JPanel {
	private JTextField textFieldAmbulance;
	private JTextField txtSelAmbu;
	private JTextField textIDMission;
	private TextArea textArea;
	private Mission mission;
	private JComboBox comboBoxMissionStatus;
	private JLabel lbSelAmbu;
	private JButton butSelAmbu;
	private JButton butAsigAmbu;
	private JLabel lblEstadoMision;
	private DynamicTree tree;
	private JButton btnCerrarMisin;

	/**
	 * Create the panel.
	 */
	public PanelMission(TextArea _textArea, Mission _mission, DynamicTree _tree) {

		textArea = _textArea;
		mission = _mission;
		tree = _tree;

		setBorder(new TitledBorder(null, "Misi\u00F3n", TitledBorder.LEADING,
				TitledBorder.TOP, null, Color.BLUE));
		setLayout(new MigLayout("", "[120.00][209.00px,grow][59.00]",
				"[][][21.00][35.00px:2.00][][][][][][][]"));

		JLabel lblInformacinBsica = new JLabel("Información Básica");
		add(lblInformacinBsica, "cell 0 0");
		lblInformacinBsica.setAlignmentX(Component.RIGHT_ALIGNMENT);
		lblInformacinBsica.setHorizontalAlignment(SwingConstants.LEFT);
		lblInformacinBsica.setFont(new Font("Tahoma", Font.BOLD, 11));

		JSeparator separator = new JSeparator();
		add(separator, "cell 0 1,grow");

		JLabel lblIdMisin = new JLabel("ID Misión");
		add(lblIdMisin, "flowy,cell 0 2,alignx left");

		textIDMission = new JTextField();
		textIDMission.setBackground(Color.WHITE);
		textIDMission.setEditable(false);
		add(textIDMission, "cell 1 2,growx");
		textIDMission.setColumns(10);

		lblEstadoMision = new JLabel("Estado Mision");
		add(lblEstadoMision, "cell 0 3");

		comboBoxMissionStatus = new JComboBox();
		add(comboBoxMissionStatus, "cell 1 3");
		comboBoxMissionStatus
				.setModel(new DefaultComboBoxModel(new String[] {"Esperando asistencia", "Esperando ambulancia", "Siendo atendido", "Camino hospital", "En hospital", "Close", "Abortar"}));

		JButton btnNewButton_2 = new JButton("Modificar Misión");
		btnNewButton_2.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				changeMissionStatus();
			}
		});
		add(btnNewButton_2, "flowx,cell 1 4,alignx center");

		JLabel lblNewLabel_1 = new JLabel("Gestión Ambulancia");
		add(lblNewLabel_1, "cell 0 5");
		lblNewLabel_1.setAlignmentX(Component.RIGHT_ALIGNMENT);
		lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11));

		JSeparator separator_1 = new JSeparator();
		add(separator_1, "cell 0 6,grow");

		textFieldAmbulance = new JTextField();
		textFieldAmbulance.setBackground(Color.WHITE);
		textFieldAmbulance.setEditable(false);
		add(textFieldAmbulance, "cell 1 7,growx");
		textFieldAmbulance.setColumns(10);

		lbSelAmbu = new JLabel("Selección Ambulancia");
		add(lbSelAmbu, "cell 0 8");

		txtSelAmbu = new JTextField();
		txtSelAmbu
				.setToolTipText("Puede poner la URL o únicamente el identificador");
		txtSelAmbu.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				if (arg0.getKeyChar() == 10) {
					assignAmbulance();
				}
			}
		});
		add(txtSelAmbu, "cell 1 8,growx");
		txtSelAmbu.setColumns(10);

		butSelAmbu = new JButton("Asignacion");
		butSelAmbu.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				assignAmbulance();
			}
		});
		add(butSelAmbu, "cell 2 8");

		butAsigAmbu = new JButton("Asignación Automática");
		butAsigAmbu.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				ambulanceAutomaticSelection();
			}

		});
		add(butAsigAmbu, "cell 1 9,alignx center");
		butAsigAmbu.setHorizontalAlignment(SwingConstants.LEFT);
		butAsigAmbu.setAlignmentY(Component.TOP_ALIGNMENT);

		JLabel lblAmbulanciaAsignada = new JLabel("Ambulancia Asignada");
		add(lblAmbulanciaAsignada, "cell 0 7");

		btnCerrarMisin = new JButton("Borrar Misión");
		btnCerrarMisin.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				deleteMission();
			}
		});
		add(btnCerrarMisin, "cell 1 4");

		completeInformation();
	}

	protected void deleteMission() {
		// Desvincular ambulancia en Storage
		Response response = CommToolkit.sendDelete(mission);
		if (response.getStatus().equals(Status.SUCCESS_NO_CONTENT)) {
			textArea.append(response.getStatus().getDescription());

			// Borrar ambulancia de la lista de ambulancias
			// 1) Peticion GET a la lista de ambulancias
			MissionList missions = (MissionList) CommToolkit
					.getRepresentation(CommToolkit.MISSIONS);

			// 2) Elimino la mision concreta de la lista
			missions.removeMission(mission.getUri());

			// 3) Peticiones PUT para actualizar el recurso completo
			Response resp = CommToolkit.doPut(missions);
			textArea.append(resp.getStatus().getDescription());

			// borramos el nodo del arbol
			tree.deleteNode(tree.getLastSelectedNode());
		} else {
			textArea.append(response.getStatus().getDescription());
		}
	}

	protected void changeMissionStatus() {
		int currentStatus = this.comboBoxMissionStatus.getSelectedIndex();
		Form form = new Form();
		form.add(Mission.STATUS, currentStatus + "");
		Status status = CommToolkit.sendPatch(mission.getUri(), form);
		if (status.equals(Status.SUCCESS_OK)) {
			this.comboBoxMissionStatus.setSelectedIndex(currentStatus);
			lblEstadoMision.setForeground(Color.BLACK);
		} else {
			lblEstadoMision.setForeground(Color.RED);
			this.txtSelAmbu.setText("");
		}
		textArea.append(status.toString());
	}

	private void completeInformation() {
		this.textIDMission.setText(mission.getIdMision() + "");
		this.textFieldAmbulance.setText(mission.getAmbulance());
		this.comboBoxMissionStatus.setSelectedIndex(mission.getEstado());
		if (mission.getAmbulance() != null) {
			hideAmbulanceSelectionPane();
		}
	}

	public JComboBox getComboBoxMissionStatus() {
		return comboBoxMissionStatus;
	}

	private void ambulanceAutomaticSelection() {
		// Consigues las ambulancias libres
		AmbulanceList list = (AmbulanceList) CommToolkit
				.getRepresentation(CommToolkit.AMBULANCES + "?estado=libre");

		// Selecciona la primera de ellas
		if (list.getListaAmbulancias().size() == 0) {
			textArea.append("No hay ambulancias libres");
			return;
		}
		String selectedAmbulance = list.getListaAmbulancias().get(0);
		// Envia la petición para cambiar el estado
		Form form = new Form();
		form.add(Mission.AMBULANCE, selectedAmbulance);
		Status status = CommToolkit.sendPatch(mission.getUri(), form);
		if (status.equals(Status.SUCCESS_OK)) {
			hideAmbulanceSelectionPane();
			textFieldAmbulance.setText(selectedAmbulance);
			lbSelAmbu.setForeground(Color.BLACK);
			// Cambia el estado del combobox
			this.comboBoxMissionStatus
					.setSelectedIndex(this.comboBoxMissionStatus
							.getSelectedIndex() + 1);
			// Repaint the ambulance
			tree.redraw(selectedAmbulance, Node.AMBULANCE);
		} else {
			lbSelAmbu.setForeground(Color.RED);
			this.txtSelAmbu.setText("");
		}
		textArea.append(status.toString());

	}

	protected void assignAmbulance() {
		String selection = txtSelAmbu.getText();
		String selectedAmbulance = null;
		if (selection.contains("http://")) {
			selectedAmbulance = selection;
		} else {
			selectedAmbulance = CommToolkit.AMBULANCES + "/" + selection;
		}
		Form form = new Form();
		form.add(Mission.AMBULANCE, selectedAmbulance);
		Status status = CommToolkit.sendPatch(mission.getUri(), form);
		if (status.equals(Status.SUCCESS_OK)) {
			hideAmbulanceSelectionPane();
			textFieldAmbulance.setText(selectedAmbulance);
			lbSelAmbu.setForeground(Color.BLACK);
			// Cambia el estado del combobox
			this.comboBoxMissionStatus
					.setSelectedIndex(this.comboBoxMissionStatus
							.getSelectedIndex() + 1);
			// Repaint the ambulance
			tree.redraw(selectedAmbulance, Node.AMBULANCE);

		} else {
			lbSelAmbu.setForeground(Color.RED);
			this.txtSelAmbu.setText("");
		}
		textArea.append(status.toString());
	}

	private void hideAmbulanceSelectionPane() {
		this.txtSelAmbu.setVisible(false);
		this.lbSelAmbu.setVisible(false);
		this.butAsigAmbu.setVisible(false);
		this.butSelAmbu.setVisible(false);
	}

}
